package com.sinochem.yunlian.ship.ucenter.schedule;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinochem.yunlian.ship.common.enums.CompanyStatus;
import com.sinochem.yunlian.ship.ucenter.biz.UcShipBiz;
import com.sinochem.yunlian.ship.ucenter.biz.UcShipLocationBiz;
import com.sinochem.yunlian.ship.ucenter.entity.UcShip;
import com.sinochem.yunlian.ship.ucenter.entity.UcShipLocation;
import com.sinochem.yunlian.ship.ucenter.rest.ShipLocationDataRest;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;

/**
 * 任务Handler的一个Demo（Bean模式）
 *
 * 开发步骤： 1、继承 “IJobHandler” ； 2、装配到Spring，例如加 “@Service” 注解； 3、加 “@JobHander”
 * 注解，注解value值为新增任务生成的JobKey的值;多个JobKey用逗号分割; 4、执行日志：需要通过 "XxlJobLogger.log"
 * 打印执行日志；
 *
 * @author xuxueli 2015-12-19 19:43:36
 */
@JobHander(value = "demoJobHandler")
@Service
public class DemoJobHandler extends IJobHandler {

	@Autowired
	private ShipLocationDataRest shipDataRest;

	@Autowired
	private UcShipBiz ucShipBiz;

	@Autowired
	private UcShipLocationBiz ucShipLocationBiz;

	@Override
	public ReturnT<String> execute(String... params) throws Exception {
		XxlJobLogger.log("XXL-JOB, Hello World.我执行了================哈哈哈哈哈哈哈哈");

		// 查询所有船舶信息
		List<UcShip> shipList = ucShipBiz.findCertifiedShipList(CompanyStatus.PASS.getCode());

		// 分批查询船舶位置信息
		if (shipList != null && shipList.size() > 0) {
			int stepLength = shipList.size() % 20 + 1;
			for (int step = 1; step < stepLength + 1; step++) {
				List<UcShip> ucShipList = shipList.subList(step, step * 20);
				String mmsis = ucShipList.stream().map(ucShip -> ucShip.getShipMmsi() + "")
						.collect(Collectors.joining(","));
				List<UcShipLocation> ucShipLocationList = shipDataRest.requestRestUrl(
						"http://shipapi.chinaports.com/shipDataApi/getShipLatestMsg", mmsis,
						"09fd2450680248cd933ac162cbfbddf9", "20171206");
				// 位置数据持久化
				// ucShipLocationBiz.addShipLocationBatch(ucShipLocationList);
			}
		} else {
			XxlJobLogger.log("yunlian ship 获取认证船数据为空,请核实!");
		}

		return ReturnT.SUCCESS;
	}

}
